package weaver.jinpin.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.OperateParam;
import com.kingdee.bos.webapi.entity.OperatorResult;
import com.kingdee.bos.webapi.entity.RepoError;
import com.kingdee.bos.webapi.entity.RepoResult;
import com.kingdee.bos.webapi.entity.RepoStatus;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.kingdee.bos.webapi.utils.CfgTools;

import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

/**
 * 拷贝 class 到 %weaver%\ecology\classbean\weaver\jinpin\action <br>
 * 拷贝 properties 到 %weaver%\ecology\WEB-INF\prop
 */
public class K3CloudAudit extends BaseBean implements Action {
	private Log log = LogFactory.getLog(K3CloudAudit.class.getName());
	private String kdFormId;

	static {
		CfgTools.setCfgFilePath();
	}

	@Override
	@SuppressWarnings("rawtypes")
	public String execute(RequestInfo requestInfo) {
		//
		String result = Action.FAILURE_AND_CONTINUE;
		String message = "";
		// 请求ID
		String requestid = requestInfo.getRequestid();
		// 表单ID
		int formid = requestInfo.getRequestManager().getFormid();
		// 获取单据编号
		String number = "";
		String retTxt = "";
		try {
			try {
				number = getKingdeeBillNo(formid, requestid);
			} catch (Exception ex) {
				message = "获取金蝶审核错误：" + ex.getMessage();
				requestInfo.getRequestManager().setMessagecontent(message);
				return result;
			}
			if (number == null || number.isEmpty()) {
				result = Action.SUCCESS;
				return result;
			}
			this.kdFormId = getKdFormId(formid);
			if (kdFormId == null || kdFormId.isEmpty()) {
				message = "金蝶对象标识未定义";
				requestInfo.getRequestManager().setMessagecontent(message);
				return result;
			}
			//
			try {
				// 生成接口参数
				OperateParam param = new OperateParam();
				List<String> numbers = new ArrayList<String>();
				numbers.add(number);
				param.setNumbers(numbers);
				// 调用接口
				K3CloudApi client = new K3CloudApi();
				OperatorResult rst = client.audit(kdFormId, param);
				// 返回数据转换为字符串，用于日志
				Gson gson = new Gson();
				retTxt = gson.toJson(rst);
				// 返回数据分析，判断是否操作成功
				RepoResult repo = rst.getResult();
				RepoStatus status = repo.getResponseStatus();
				if (status.isIsSuccess()) {
					message = "调用金蝶审核成功";
					result = Action.SUCCESS;
				} else {
					message = getErrorMessage("审核", status);
					requestInfo.getRequestManager().setMessagecontent(message);
				}
			} catch (Exception ex) {
				message = "调用金蝶审核异常：" + ex.getMessage();
				requestInfo.getRequestManager().setMessagecontent(message);
			}
		} finally {
			String logtxt = "K3CloudAudit RequestId:%s, BillNo:%s, Result:%s, Message:%s";
			logtxt = String.format(logtxt, requestid, number, retTxt, message);
			log.info(logtxt);
		}
		return result;
	}

	public static String getErrorMessage(String op, RepoStatus status) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("调用金蝶" + op + "错误：");
		ArrayList<RepoError> errors = status.getErrors();
		for (RepoError error : errors) {
			buffer.append(error.getMessage()).append("；");
		}
		return buffer.toString();
	}

	@SuppressWarnings("deprecation")
	public static String getKingdeeBillNo(int formid, String requestid) throws Exception {
		String number = null;
		String numberKey = "";
		formid = Math.abs(formid);
		switch (formid) {
		case 16:
			numberKey = "sqdh";
			break;
		case 65:
			numberKey = "sqdh";
			break;
		default:
			throw new Exception(String.format("未定义单据：%s", formid));
		}
		String tableName = String.format("formtable_main_%s", formid);
		String sql = "SELECT %s FROM %s WHERE requestid = %s and erpid is not null and erpid > 0";
		sql = String.format(sql, numberKey, tableName, requestid);
		RecordSet recordSet = new RecordSet();
		recordSet.executeSql(sql);
		if (recordSet.next()) {
			number = recordSet.getString(numberKey);
		}
		if (number == null || number.isEmpty()) {
			throw new Exception(String.format("未找到单据编码：%s", requestid));
		}
		return number;
	}

	public static String getKdFormId(int formid) {
		formid = Math.abs(formid);
		switch (formid) {
		case 16:
			return "SAL_DELIVERYNOTICE";
		case 65:
			return "SAL_DELIVERYNOTICE";
		default:
			return null;
		}
	}
}
